package com.scrx.ymg.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.scrx.ymg.entity.Address;
import com.scrx.ymg.entity.AgentInfo;
import com.scrx.ymg.entity.BankAccount;
import com.scrx.ymg.entity.DirectInfo;
import com.scrx.ymg.entity.GoodsType;
import com.scrx.ymg.entity.HeadWithdarw;
import com.scrx.ymg.entity.OtherInfo;
import com.scrx.ymg.entity.ProductEvaluate;
import com.scrx.ymg.entity.SuperMarketEntrepot;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.entity.SupermarketDrawings;
import com.scrx.ymg.entity.SupermarketMoney;

import com.scrx.ymg.entity.YmgHead;
import com.scrx.ymg.service.address.IAddressService;
import com.scrx.ymg.service.agent.IAgentService;
import com.scrx.ymg.service.entrepot.ISuperMarketEntrepotService;
import com.scrx.ymg.service.supermarket.ISuperMarketService;
import com.scrx.ymg.util.LatLonUtil;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/superMarketAction")
public class SuperMarketAction {

	@Autowired
	private ISuperMarketService sms;

	@Autowired
	private ISuperMarketEntrepotService smes;

	@Autowired
	private IAgentService ages;
	
	@Autowired
	private IAddressService adds;

	/**
	 * 登陆
	 * 
	 * @param username
	 * @param password
	 * @param response
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/login", produces = "text/json;charset=UTF-8")
	public String login(String username, String password, String typeID) throws IOException {
		ModelAndView mav = new ModelAndView();
		Gson gson = new Gson();
		Object obj = sms.loginByTypeID(username, password, typeID);
		String str = null;

		if (typeID.equals("0")) {// 总部
			str = gson.toJson((YmgHead) obj);
		} else if (typeID.equals("1")) {// 代理
			if(obj!=null){
				AgentInfo info =(AgentInfo)obj;
				if (info.getStatus()==2) {
					return "250";
				}
			}
			str = gson.toJson((AgentInfo) obj);
		} else if (typeID.equals("2")) {// 异业
			if(obj!=null){
				OtherInfo info =(OtherInfo)obj;
				if (info.getOtherStatus()==3||info.getOtherStatus()==2||info.getOtherStatus()==5) {
					return "250";
				}
			}
			str = gson.toJson((OtherInfo) obj);
		} else if (typeID.equals("3")) {// 超市
			if(obj!=null){
				SuperMarketInfo info =(SuperMarketInfo)obj;
				if (info.getStatus()==3||info.getStatus()==4||info.getStatus()==5) {
					return "250";
				}
			}
			str = gson.toJson((SuperMarketInfo) obj);
		}else if (typeID.equals("4")) {// 直营
			if(obj!=null){
				DirectInfo info =(DirectInfo)obj;
				if (info.getStatus()==1) {
					return "250";
				}
			}
			str = gson.toJson((DirectInfo) obj);
		}
		return str;
	}

	@RequestMapping("/tojsp")
	public ModelAndView tojsp() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/YMGback/super/chaoshi.jsp");
		return mav;
	}

	/**
	 * 加载商品分类
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getGoodsType")
	public List<GoodsType> getjsp() {
		List<GoodsType> goodslist = sms.findAll();
		return goodslist;
	}

	/**
	 * 根据商品分类加载二级分类
	 * 
	 * @param typeID
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getGoodsType2")
	public List<GoodsType> getjsp2(String typeID) {
		if (typeID.equals("0")) {
			return null;
		} else {
			List<GoodsType> goodslist = sms.findOne(typeID);
			return goodslist;
		}
	}

	@InitBinder("address")
	public void initBinder1(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("address.");
	}

	@InitBinder("user")
	public void initBinder2(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("user.");
	}

	/**
	 * 根据经纬度查询距离最近的超市
	 * 
	 * @param address
	 *            用户地址
	 * @param lon
	 *            用户经度
	 * @param lat
	 *            用户纬度
	 * @throws IOException
	 * @throws JSONException
	 */
	@ResponseBody
	@RequestMapping(value = "/skipPrefecture", produces = "text/json;charset=UTF-8")
	public String skipPrefecture(double lon, double lat) throws JSONException, IOException {
		SuperMarketInfo superinfo = getLatelySuper(lon,lat);
		JSONObject json = JSONObject.fromObject(superinfo);
		// 3.返回超市信息
		return json.toString();
	}
	
	public SuperMarketInfo getLatelySuper(double lon, double lat){
		// 1.根据经纬度查询一公里范围内超市
				LatLonUtil latlon = new LatLonUtil();
				double[] lalon = latlon.getAround(lat, lon, 1000);// 1000米为1公里
				List<SuperMarketInfo> list = sms.findSuperListBylatlon(lalon[0], lalon[1], lalon[2], lalon[3]);
				// 2.锁定一公里范围内最近的超市
				double temp = 1000;
				double min = 0;
				SuperMarketInfo superinfo = null;
				SuperMarketInfo minsuper=null;
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						superinfo = list.get(i);
						if(superinfo.getStatus()==0){
						min = latlon.getDistance(lon, lat, list.get(i).getLongitude(), list.get(i).getLatitude());
						if (temp > min) {
							temp = min;
							minsuper = list.get(i);
						 }
						}
					}
				}
				if(minsuper!=null){
					return minsuper;
				}
				// 3.返回超市信息
				return superinfo;
	}

	/**
	 * 得到超市首页广告和推荐商品
	 * 
	 * @param id
	 */
	@ResponseBody
	@RequestMapping(value = "/getSuperMarketIndex", produces = "text/json;charset=UTF-8")
	public String getSuperMarketIndex(String superID,String userId) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		SuperMarketInfo  info =sms.findByID(Integer.parseInt(superID));
		//默认超市状态不是正常营业
		if(info.getStatus()!=0){
			Address add= adds.getAddress(userId,superID);
			info=getLatelySuper(Double.parseDouble(add.getLongitudeNum()), Double.parseDouble(add.getLatitudeNum()));
		}
		if(info.getStatus()==0){
			List<SuperMarketEntrepot> list = smes.getEntrepotByID(superID);
			List<SuperMarketEntrepot> hot =smes.getHotBySuperId(superID,1);
			map.put("list", list);
			map.put("hot", hot);
			map.put("superId", info.getId());
			Gson gson = new Gson();
			String str = gson.toJson(map);
			return str;
		}else if(info.getStatus()==1){
			return "251";
		}else{
			return "252";
		}
		
	}

	/**
	 * 新建超市
	 * 
	 * @param superInfo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createSuperMarket", produces = "text/json;charset=UTF-8")
	public String createSuperMarket(SuperMarketInfo superInfo,MultipartFile cssj, MultipartFile yyzz,
			MultipartFile deliver, MultipartFile card) {
//		LatLonUtil latlon = new LatLonUtil();
//		double[] lalon = latlon.getAround(superInfo.getLatitude(), superInfo.getLongitude(), 200);// 1000米为1公里
//		List<SuperMarketInfo> list = sms.findSuperListBylatlon(lalon[0], lalon[1], lalon[2], lalon[3]);
//		if (list.size() > 0) {
//			return "250";
//		}
		// 判断超市名称,电话账号,经纬度,所属区域,
		String msg = ages.createSuperMarket(superInfo, superInfo.getAgentId(), cssj, yyzz, deliver, card);
		return msg;
	}
	/**
	 * 恢复超市.重置超市信息
	 * @param superInfo
	 * @param cssj
	 * @param yyzz
	 * @param deliver
	 * @param card
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateSuperMarket", produces = "text/json;charset=UTF-8")
	public String updateSuperMarket(SuperMarketInfo superInfo,MultipartFile cssj, MultipartFile yyzz,
			MultipartFile deliver, MultipartFile card) {
//		LatLonUtil latlon = new LatLonUtil();
//		double[] lalon = latlon.getAround(superInfo.getLatitude(), superInfo.getLongitude(), 200);// 1000米为1公里
//		List<SuperMarketInfo> list = sms.findSuperListBylatlon(lalon[0], lalon[1], lalon[2], lalon[3]);
//		if (list.size() > 0) {
//			return "250";
//		}
		// 判断超市名称,电话账号,经纬度,所属区域,
		//SuperMarketInfo info =sms.findByID(superInfo.getId());
		//superInfo.setAgentId(info.getAgentId());
		String msg = ages.updateSuperMarket(superInfo, superInfo.getAgentId(), cssj, yyzz, deliver, card);
		return msg;
	}
	
	
	

	/**
	 * 判断超市坐标附近N米内是否有超市
	 * 
	 * @param account
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/longitudeAndLatitudeExists", produces = "text/json;charset=UTF-8")
	public String longitudeAndLatitudeExists(double longitude, double latitude) {
		// 1.根据经纬度查询一公里范围内超市
		LatLonUtil latlon = new LatLonUtil();
		double[] lalon = latlon.getAround(latitude, longitude, 300);// 1000米为1公里
		List<SuperMarketInfo> list = sms.findSuperListBylatlon(lalon[0], lalon[1], lalon[2], lalon[3]);
		if (list.size() > 0) {
			return "false";
		}
		return "false";
	}



	/**
	 * 得到超市营业额
	 * 
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSupermarketMoneyInfo", produces = "text/json;charset=UTF-8")
	public String getSupermarketMoneyInfo(int superId) {
		SupermarketMoney money = sms.getSupermarketMoneyInfo(superId);
		Gson gson = new Gson();
		return gson.toJson(money);
	}

	/**
	 * 超市提现
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/superMarketWithdraw", produces = "text/json;charset=UTF-8")
	public String superMarketWithdraw(int superId) {
		String msg = sms.superMarketWithdraw(superId);
		Gson gson = new Gson();
		return gson.toJson(msg);
	}

	/**
	 * 是否填写超市银行账户信息
	 * 
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isOKsuperMarketWithdraw", produces = "text/json;charset=UTF-8")
	public String isOKsuperMarketWithdraw(int superId) {
		return sms.isNullBankAccountInfo(superId);
	}
	/**
	 * 是否填写代理商银行账户信息
	 * 
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isOKAgentWithdraw", produces = "text/json;charset=UTF-8")
	public String isOKAgentWithdraw(int agentId) {
		return sms.isNullBankAccountInfoAgent(agentId);
	}
	/**
	 * 是否填写异业商家银行账户信息
	 * 
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isOKOtherWithdraw", produces = "text/json;charset=UTF-8")
	public String isOKOtherWithdraw(int otherId) {
		return sms.isNullBankAccountInfoOther(otherId);
	}
	
	/**
	 * 是否填写直营商家银行账户信息
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isOKDirectWithdraw", produces = "text/json;charset=UTF-8")
	public String isOKDirectWithdraw(int directId) {
		return sms.isNullBankAccountInfoDirect(directId);
	}

	/**
	 * 提交填写超市银行账户信息
	 * 
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/setBankAccountInfo", produces = "text/json;charset=UTF-8")
	public String setBankAccountInfo(BankAccount bankAccount) {
		return sms.createBankAccountInfo(bankAccount);
	}

	/**
	 * 得到总部提现设置
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getHeadWithdarw", produces = "text/json;charset=UTF-8")
	public String getHeadWithdarw() {
		HeadWithdarw head = sms.getHeadWithdarw();
		Gson gson = new Gson();
		return gson.toJson(head);
	}
    
	/**
	 * 查询超市提现记录
	 * @param drawing
	 * @param pageNum
	 * @param pageCount
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSupermarketDrawings", produces = "text/json;charset=UTF-8")
	public String getSupermarketDrawings(SupermarketDrawings drawing, int pageNum, int pageCount) {
		Map<Object, Object> map = sms.getSupermarketDrawings(drawing, pageNum, pageCount);
		Gson gson = new Gson();
		return gson.toJson(map);
	}
	
	/**
	 * 查询超市
	 * @param drawing
	 * @param pageNum
	 * @param pageCount
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllSuperMarketInfo", produces = "text/json;charset=UTF-8")
	public String getAllSuperMarketInfo(SuperMarketInfo info,int pageNum, int pageCount){
		Map<Object, Object> map =sms.getAllSuperMarketInfo(info,pageNum,pageCount);
		Gson gson = new Gson();
		return gson.toJson(map);
	}
	
	/**
	 * 查询超市支付方式
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSuperPayment_mode", produces = "text/json;charset=UTF-8")
	public String getSuperPayment_mode(int superId){
		SuperMarketInfo info = sms.findByID(superId);
		return info.getPaymentMode().toString();
	}
	
	/**
	 * 查询超市信息
	 * @param superId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSuperInfo", produces = "text/json;charset=UTF-8")
	public String getSuperInfo(int superId){
		SuperMarketInfo info = sms.findByID(superId);
		Gson gson = new Gson();
		return gson.toJson(info);
	}
	
	/**
	 * 根据商品id
	 * @param entrepotId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getSuperMarketEntrepot", produces = "text/json;charset=UTF-8")
	public String getSuperMarketEntrepot(int entrepotId){
		SuperMarketEntrepot en=smes.getEntrepotByEntID(entrepotId+"");
		List<ProductEvaluate> list =smes.getProductEvaluateByIdAndType(entrepotId,1);
		Map<Object,Object> map=new HashMap<Object, Object>();
		map.put("SuperMarketEntrepot", en);
		map.put("Evaluates", list);
		Gson gson = new Gson();
		return gson.toJson(map);
	}
	
	


}
